// errand/components/cancel/index.js
Component({

    /**
     * 组件的属性列表
     */
    properties: {
        show: {
            type: Boolean,
            default: false
        }
        
    },

    /**
     * 组件的初始数据
     */
    data: {
        isEnd: false,
        selected: [],
        list: []
    },
    created: function(){
        this.getList(0);
    },
    /**
     * 组件的方法列表
     */
    methods: {
        //获取分类
        getList: function(n) {
            let {selected, list} = this.data;
            wx.$http({
                load: true,
                url: `/business/category-tree/${n}`,
                method: 'get',
                data: {},
            }).then((res) => {
                let arr = res.data;
                arr.forEach(item=>{
                    item.isCur = false;
                }) 
                if(arr.length){
                    this.setData({
                        list: arr,
                    })
                } else {
                    this.setData({
                        isEnd: true
                    })
                    this.setListCur();
                }
            })
        },
        //选中分类
        selectClass: function(e) {
            let {selected,isEnd} = this.data;
            let obj = e.currentTarget.dataset.obj;
            if(isEnd){
                selected[selected.length-1] = obj;
                this.setData({
                    selected: selected
                })
                this.setListCur();
            }else {
                selected.push(obj);
                this.setData({
                    selected: selected
                })
                this.getList(obj.id);
            }
            
        },
        //切换分类
        changeClass: function(e) {
            let {selected} = this.data;
            let index = e.currentTarget.dataset.index;
            selected.length = index;
            this.setData({
                selected: selected,
                isEnd: false 
            })
            this.getList(index>0?selected[index-1].id : 0);
        },
        //设置列表为选中
        setListCur: function() {
            let {list,selected} = this.data;
            list.forEach(item=>{
                item.isCur = false;
                selected.forEach(items=>{
                    if(item.id == items.id){
                        item.isCur = true;
                    }
                })
            })
            this.setData({
                list: list
            })
        },
        //关闭
        close: function() {
            this.triggerEvent('confirm');  
        },
        //保存分类
        save: function() {
            let {isEnd,selected} = this.data;
            if(isEnd){
                this.triggerEvent('confirm',{change: true, selected:selected});  
            }
        }

    }
})